﻿using JESAI.Application.Abstractions.Admin;
using JESAI.Application.Abstractions.Admin.Dtos.Department;
using JESAI.Application.Abstractions.Admin.Dtos.Role;
using JESAI.Application.Abstractions.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Core;
using JESAI.Core.Attributes;
using JESAI.Core.Extensions;
using JESAI.Core.Util.Helpers;
using JESAI.Platform.Domain.Admin.Repositories;
using JESAI.Platform.Domain.Sys.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Admin
{
    [AppService]
    internal class DepartmentService : IDepartmentService
    {
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IUser _user;
        public DepartmentService(IDepartmentRepository departmentRepository, IUser user)
        {
            _departmentRepository = departmentRepository;
            _user = user;
        }

        public async Task DeleteDepartment(string id)
        {
            await _departmentRepository.DeleteByIdAsync(id);
        }

        public async Task DeleteDepartments(string[] ids)
        {
            await _departmentRepository.DeleteByIdsAsync(ids);
        }

        public async Task<List<DepartmentTreeDto>> QueryAllDepartmentTrees(QueryAllDepartmentInput input)
        {
            var modelList = _departmentRepository._DbQueryable
                               .WhereIF(input.IsValid.HasValue, it => it.IsValid == input.IsValid)
                               .WhereIF(!input.Name.IsEmpty(), it => it.Name == input.Name)
                               .WhereIF(!input.Director.IsEmpty(), it => it.Director == input.Director)
                                .WhereIF(!input.Phone.IsEmpty(), it => it.Phone == input.Phone)
                                .WhereIF(!input.Email.IsEmpty(), it => it.Email == input.Email)
                               .ToList();

            return modelList.MapTo<List<DepartmentTreeDto>>();
        }

        public async Task UpdateOrInsert(SetDepartmentInput input)
        {
            var model = input.MapTo<DepartmentEntity>();
            if (model.Id.IsNullOrEmpty())
            {
                model.Id = Guid.NewGuid().ToString();
                model.CreateTime = DateTime.Now;
                model.Cid = _user.Id.ToLong();
                await _departmentRepository.InsertAsync(model);
            }
            else
            {
                model.UpdateTime = DateTime.Now;
                model.Uid = _user.Id.ToLong();
                await _departmentRepository.UpdateAsync(model);
            }
        }
    }
}
